package cn.dida.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.dida.exception.BizzException;
import cn.dida.model.HttpResponseBodyWrapper;
/**
 * <p>上传公共类</p>
 * @author weiwei
 *
 */
@Controller
@RequestMapping(value = "/upload")
public class UploadController extends BaseController {
    private Log loger = LogFactory.getLog(UploadController.class);
    @Value("${upload.path.pic}")
    private String picStoragePath;

    /**
     * 上传
     * @param request
     * @param type 节点类型（自定义）
     * @return Object
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/pic")
    public Object upload(HttpServletRequest request, Integer type) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        MultipartFile headimg = multipartRequest.getFile("file");


        //根据上传的类型，存储到不同的子目录
        if(type == null){
        	type=1;
        }
        String childPath = "tmp";
        if (type == 1) {
            childPath = "product";//产品图片路径
        } else if (type == 2) {
            childPath = "branch";
        }else if(type == 3){
        	childPath = "activity";//活动图片路径
        }else if(type == 4){
        	childPath = "prize";//奖品图片路径
        }else if(type == 5){
        	childPath = "bills";//单据凭证图片路径
        }

        //限制图片大小1M以内
        if (headimg.getSize() > 1024 * 1024) {
            throw new BizzException(BizzException.error_code_invalid_request, "图片太大啦，请上传1M以内的图片");
        }

        //step1:构建文件输出路径
        String uploadDir = picStoragePath + "/" + childPath;
        String fileName = generateFileName(headimg.getOriginalFilename());

        //step2:判断输出目录是否为空，为空则创建
        File tmp = new File(uploadDir);
        if (!tmp.exists()) {
            tmp.mkdirs();
        }
        //step3:存储文件
        String outFilePath = uploadDir + "/" + fileName;
        OutputStream os = new FileOutputStream(new File(outFilePath));
        IOUtils.copy(headimg.getInputStream(), os);
        os.close();

        //step4:压缩
        //ImageCompressUtil.zipImageFile(outFilePath, 100, 100, 1, "");


        return new HttpResponseBodyWrapper("/" + childPath + "/" + fileName);
    }


    protected String generateFileName(String originalFilename) {
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replaceAll("-", "");
        String fileName = uuid + "." + originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
        return fileName;
    }
}
